package com.tensquare.notice.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

/**
 * @Author: xxx
 * @Date: 2022/11/13 21:34
 * @Description: netty服务端
 */
public class NettyServer {
    
    public void start(int port){
        System.out.println("准备启动启动netty...");
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        
        //用来处理新连接的
        NioEventLoopGroup boos = new NioEventLoopGroup();
        //用来处理业务逻辑的，读写
        NioEventLoopGroup worker = new NioEventLoopGroup();
        
        serverBootstrap.group(boos, worker)
                //.localAddress(port)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        //请求消息解码器
                        //给流水线添加“工人”
                        channel.pipeline().addLast(new HttpServerCodec());
                        //将多个消息转换为单一的request或者response对象
                        channel.pipeline().addLast(new HttpObjectAggregator(65536));
                        //处理webSocket的消息时间
                        channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
                        //创建自己的webSocket的处理器，就是用来编写业务逻辑的
                        MyWebSocketHandler myWebSocketHandler=new MyWebSocketHandler();
                        channel.pipeline().addLast(myWebSocketHandler);
                    }
                }).bind(port);
        
    }
    
    
}
